package com.vms.control.weight.ui;

import java.util.Map;
import java.util.TreeMap;

import com.vms.NetLog;

import android.content.Context;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ViewAnimator;

public class AnimationHolder {

	public AnimationHolder(Context context) {
		super();
		this.mContext = context;
	}

	public enum AnimVariant {
		FIRST,
		SECOND
	}
	
	private Context mContext;
	private Map<AnimVariant,Map<Integer,AnimationPair>> mAnimStore 
		= new TreeMap<AnimVariant,Map<Integer,AnimationPair>>();
	

	public AnimationHolder put (AnimVariant variant, ViewAnimator targetView, int in, int out) {
		return put(variant, targetView, 
				AnimationUtils.loadAnimation(mContext,in),
				AnimationUtils.loadAnimation(mContext,out));
	}
	
	public AnimationHolder put (AnimVariant variant, ViewAnimator targetView, Animation in, Animation out) {
		
		if(mAnimStore.get(variant) == null){
			TreeMap<Integer, AnimationHolder.AnimationPair> animForView =new TreeMap<Integer, AnimationHolder.AnimationPair>();
			animForView.put(targetView.hashCode(), new AnimationPair(in, out));	
			mAnimStore.put(variant,animForView);
		} else {
			mAnimStore.get(variant).put(targetView.hashCode(), new AnimationPair(in, out));
		}
			
		return this;
	}
	
	public void applyThrow (AnimVariant variant, ViewAnimator targetView) {
			AnimationPair anim = mAnimStore.get(variant).get(targetView.hashCode());
			
			if( targetView.getInAnimation() == null || !targetView.getInAnimation().equals(anim.in))
				targetView.setInAnimation(anim.in);
			if( targetView.getOutAnimation() == null || !targetView.getOutAnimation().equals(anim.out))
				targetView.setOutAnimation(anim.out);
	}
	
	public void applySilent (AnimVariant variant, ViewAnimator targetView) {
		try {
			applyThrow(variant, targetView);
		} catch (Exception e) {}
	}
	
	public boolean apply (AnimVariant variant, ViewAnimator targetView) {
		try {
			applyThrow(variant, targetView);
			return true;
		} catch (Exception e) {
			NetLog.dd("Not found valiant(%s) or targetView",variant.name());
			e.printStackTrace();
			return false;
		}
	}
	
	static class AnimationPair {
		public AnimationPair(Animation in, Animation out) {
			super();
			this.in = in;
			this.out = out;
		}
		public final Animation in;
		public final Animation out;
	}
}
